﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using OnePiece.Core.Extension.Paging;


namespace OnePiece.Ui.Controls
{
    public static class GridHelper
    {
        /// <summary>
        /// Returns the list in jqGrid json specific formar
        /// </summary>
        /// <param name="query">The item to be formated</param>
        /// <param name="total">The total pages to be returned for jqGrid</param>
        /// <param name="page">The current page of the jqGrid</param>
        /// <param name="records">The total number of items in the list</param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public static JsonResult ToGridJsonResult(this IQueryable query, int total, int page, long records, params string[] fields)
        {
            if (fields.Count() == 0)
            {
                var pInfoFields = query.ElementType.GetProperties();
                var fieldCount = pInfoFields.Count();
                fields = new string[fieldCount];
                for (int i = 0; i < fieldCount; i++)
                    fields[i] = pInfoFields[i].Name;
            }

            var rows = new List<object>();
            

            foreach (var obj in query)
            {
                var type = obj.GetType();

                var propertyList = new List<string>();
                var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                foreach (var property in properties)
                {
                    var o = property.GetValue(obj, null);
                    propertyList.Add(o == null ? "" : o.ToString());
                }
                var id = propertyList[0];

                rows.Add(new { id, cell = propertyList });

            }
            var result = new JsonResult { Data = new { page, total, records, rows } };
            return result;
        }



        public static JsonResult ToGridJsonResult(this IQueryable query, PageExtensionHelper pagingHelper)
        {
            return ToGridJsonResult(query, pagingHelper.TotalPages, pagingHelper.PageIndex, pagingHelper.TotalItems);
        }

    }
}